#include<iostream>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<cstdlib>
#include<cstdio>
using namespace std;
int main()
{
  //一个子进程的等待
  //pid_t id = fork();
  //if(id==0)
  //{
  //  //子进程
  //  int count =10;
  //  while(count--)
  //  {
  //    cout<<"I am child: PID:"<<getpid()<<" PPID:"<<getppid()<<endl;
  //    sleep(1);
  //  }
  //  exit(1);
  //}

  ////father
  //int status = 0;
  //pid_t ret = wait(&status);
  ////等待成功
  //if(ret>0)
  //{
  //  cout<<"wait child success!!!"<<endl;
  //  if(WIFEXITED(status))//正常退出，退出码才有意义，被信号杀掉退出码没意义
  //  {
  //    //正常退出
  //    cout<<"exit code: "<<WEXITSTATUS(status)<<endl;
  //  }
  //}
  //sleep(3);
  //阻塞等待
  // pid_t ids[10];
  // for(int i=0;i<10;i++)
  // {
  //   pid_t id =fork();
  //   if(id==0)
  //   {
  //     //child
  //     cout<<"child process created successfully...PID: "<<getpid()<<endl;
  //     //printf("child process created successfully...PID:%d\n",getpid());
  //     sleep(3);
  //     exit(i);
  //   }
  //   //father
  //   ids[i]=id;
  //   sleep(1);
  // }
  // sleep(3);
  // for(int i=0;i<10;i++)
  // {
  //   int status =0;
  //   pid_t ret = waitpid(ids[i],&status,0);
  //   if(ret>=0)
  //   {
  //     printf("wait child success...PID:%d\n",ids[i]);
  //     if(WIFEXITED(status))
  //     {
  //       //exit normal
  //       printf("exit code:%d\n",WEXITSTATUS(status));
  //     }
  //     else 
  //     {
  //       //signal killed
  //       printf("killed by signal %d\n",status&0x7f);
  //     }
  //   }
  // }

  //非阻塞等待
  pid_t id =fork();
  if(id==0)
  {
    //child
    //printf("child process created successfully...PID:%d\n",getpid());
    int count = 5;
    while(count--)
    {
       
    cout<<"child process created successfully...PID: "<<getpid()<<endl;
    sleep(1);

    }
    exit(1);
  }
  //father

while(1){
  int status =0;
  pid_t ret = waitpid(id,&status,WNOHANG);
  if(ret>0)
  {
    printf("wait child success...PID:%d\n",id);
    if(WIFEXITED(status))
    {
      //exit normal
      printf("exit code:%d\n",WEXITSTATUS(status));
      break;
    }

  }
  else if(ret==0){
    printf("father do other things...\n");
    sleep(5);
  }
  else 
  {
    printf("waitpid error...\n");
    break;
  }
}

return 0;
}
